<?php

class AttachmentController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	
	public $defaultAction='admin';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // only allow authenticated user to get access to the system.
				'actions'=>array('index','view','create','update','admin','delete' ,'assignAttachment', 'processAssign'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$model->dealId)))
		{
			if(!Yii::app()->user->checkAccess('customerInfoAccess',array('customerId'=>$model->customerId)))
				throw new CHttpException(403,'You do not have permission to view the attachments.');
		}		
		//Set filter for attachment files.
		$attachmentFile=new AttachmentFile('search');
		$attachmentFile->unsetAttributes();  // clear any default values
		$attachmentFile->attachmentId=$id;
		
		if(isset($_GET['AttachmentFile']))
			$attachmentFile->attributes=$_GET['AttachmentFile'];
		
		$this->render('view',array(
			'model'=>$model,
			'attachmentFile'=>$attachmentFile,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($dealId)
	{
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
			throw new CHttpException(403,'You do not have permission to create attachment for this deal.');
		
		$model=new Attachment;
		$model->dealId=$dealId;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Attachment']))
		{
			$model->attributes=$_POST['Attachment'];
			if($model->save()){
				@mkdir(Yii::app()->params['attachmentFileLocation']
					.DIRECTORY_SEPARATOR.$model->dealId
					.DIRECTORY_SEPARATOR.$model->id);
				$this->redirect(array('view','id'=>$model->id));
			}
		}
		
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$model->dealId)))
			throw new CHttpException(403,'You do not have permission to update the attachment.');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Attachment']))
		{
			$model->attributes=$_POST['Attachment'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model=$this->loadModel($id);
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$model->dealId)))
			throw new CHttpException(403,'You do not have permission to delete the attachment.');
		
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			
			// delete the directory and the contains of the given attachment
			$directory=Yii::app()->params['attachmentFileLocation']
					.DIRECTORY_SEPARATOR.$model->dealId
					.DIRECTORY_SEPARATOR.$model->id;
			//DataUtil::rrmdir($directory);
			// delete related files and not delete the folder.
			foreach ($model->attachmentFiles as $file) {
				@unlink($directory.DIRECTORY_SEPARATOR.$file->storeFileName);
			}
			
			// delete the record in db
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? 
					$_POST['returnUrl'] : array('admin','dealId'=>$model->dealId));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
/*	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Attachment');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}*/

	/**
	 * Manages all models.
	 */
	public function actionAdmin($dealId)
	{
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
			throw new CHttpException(403,'You do not have permission to browse attachments of this deal.');
		
		$model=new Attachment('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Attachment']))
			$model->attributes=$_GET['Attachment'];
		
		$model->dealId = $dealId;
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 * @return Attachment object
	 */
	public function loadModel($id)
	{
		$model=Attachment::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
/*	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='attachment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}*/
	
	public function actionAssignAttachment($dealId)
	{
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
			throw new CHttpException(403,'You do not have permission to assign attachment to the deal.');
		
		$model=new Attachment('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Attachment']))
			$model->attributes=$_GET['Attachment'];
			
		// limit Attachment.
		$critetia = new CDbCriteria();
		$critetia->with = 'customer';
		$critetia->condition = 't.dealId IS NULL';
		$critetia->compare('t.createUserId', Yii::app()->user->id);
		
		// limit result by filter.
		if(!empty($model->customerId))
		{
			$names = split(' ', $model->customerId);
			if(count($names) > 1)
			{
				$critetia->condition .= ' AND (customer.firstName LIKE "%'.$names[0].'%"
				 AND customer.lastName LIKE "%'.$names[1].'%")';
			}
			else 
			{		
				$critetia->condition .= ' AND (customer.firstName LIKE "%'.$model->customerId.'%"
				 OR customer.lastName LIKE "%'.$model->customerId.'%")';
			}
		}
		if(!empty($model->name))
			$critetia->compare('name', $model->name, true);
		
		if(!empty($model->notes))
			$critetia->compare('notes', $model->notes, true);
		
		$dataProvider = new CActiveDataProvider('Attachment', array(
			'criteria'=>$critetia,
		));
		
		$deal = Deal::model()->findByPk($dealId);
		
		$this->render('assignAttachment',array(
			'dataProvider'=>$dataProvider,
			'deal'=>$deal,
			'model'=>$model,
		));
	}
	
	public function actionProcessAssign()
	{
		if(!isset($_POST['assignedAttachments']) || !isset($_POST['dealId'])){
			throw new CHttpException(403,'Informtion is not complete, can not process it!');
		}
		$attachmentIds=explode(',', $_POST['assignedAttachments']);
		$dealId = $_POST['dealId'];
		
		//Check Access control
		if(!Yii::app()->user->checkAccess('dealInfoAccess',array('dealId'=>$dealId)))
		{
			throw new CHttpException(403,'You do not have permission to process the deal.');
		}
		
		foreach ($attachmentIds as $id){
			$model = $this->loadModel($id);
			$model->dealId = $dealId;
			if ($model->save()) {
				// move file when customer id is not same as deal id.
				if($model->customerId != $model->dealId)
				{
					$oldPath = Yii::app()->params['attachmentFileLocation']
						.DIRECTORY_SEPARATOR.$model->customerId
						.DIRECTORY_SEPARATOR.$model->id;
					$newPath = Yii::app()->params['attachmentFileLocation']
						.DIRECTORY_SEPARATOR.$model->dealId
						.DIRECTORY_SEPARATOR.$model->id;
						
					@mkdir($newPath);
					$files = AttachmentFile::model()->findAll('attachmentId = :attachmentId', array(':attachmentId'=>$model->id));
					
					$result = true;
					
					foreach ($files as $file)
        				$result = rename($oldPath.DIRECTORY_SEPARATOR.$file->storeFileName, $newPath.DIRECTORY_SEPARATOR.$file->storeFileName);
				}
			}
			else {
				throw new CHttpException(404,'Datebase Error!');
			}
			
		}
		
		//Return to deal view page.
		$this->redirect(array('attachment/admin','dealId'=>$dealId));
	}
}
